# -*- coding: UTF-8 -*-
# 调用mWDN-lstm，实现一定时间内订单总量的预测（单变量）

import tensorflow as tf
import numpy as np
import os
import sys
from Models_Train import mWDN_lstm
import matplotlib as mpl
from Utils import data_process

mpl.use("Agg")
import matplotlib.pyplot as plt

# 预测粒度
PREDICT_UNIT = 5
DATA_ROOT = mWDN_lstm.DATA_ROOT
DATA_NAME = 'order_weight'
SHEET_NAME = 'day'
LEN_TEST = 90
FEATURE_NUM = 1
use_normal = True
TIME_STEP = mWDN_lstm.TIME_STEP

# 获取预测数据
LEN_DATA = data_process.getlen_data(DATA_ROOT, DATA_NAME, sheetname=SHEET_NAME)
train_data, test_data = data_process.load_data(DATA_ROOT, DATA_NAME, LEN_DATA, LEN_TEST, sheetname=SHEET_NAME,
                                               feature=FEATURE_NUM, normal=use_normal)  # 一维数组
test_x, test_y = data_process.generate_data(test_data, TIME_STEP)  # (len of test, 1, timestep); (len of test, 1)
test_x = np.reshape(test_x, [test_x.shape[0], test_x.shape[1]])
test_y = np.reshape(test_y, [test_y.shape[0], 1])

test_x = test_x[-2:, :]
# test_x = np.reshape(test_x, (1, test_x.shape[0]))  # (1,40)
# print test_x, test_x.shape
TEST_X = np.array(test_x[-1:, :]).squeeze()

# 预测过程
saver = tf.train.import_meta_graph(
    mWDN_lstm.BASE_DIR + "/LOG_mWDN-LSTM_order_weight/MODEL_order_weight_mWDN-LSTM_LOSS.ckpt.meta")
with tf.device('/gpu:0'):
    config = tf.ConfigProto()  # 配置tf.Session的运算方式
    config.gpu_options.allow_growth = True  # 当使用GPU时候，Tensorflow运行自动慢慢达到最大GPU的内存
    config.allow_soft_placement = True  # 如果指定设备不存在，允许TF自动分配设备
    config.log_device_placement = False
    sess = tf.Session(config=config)
    # saver.restore(sess, tf.train.latest_checkpoint(mWDN_lstm.BASE_DIR + "/" + mWDN_lstm.LOG_DIR))
    saver.restore(sess, mWDN_lstm.BASE_DIR + "/LOG_mWDN-LSTM_order_weight/MODEL_order_weight_mWDN-LSTM_LOSS.ckpt")
    graph = tf.get_default_graph()  # 加载默认图
    input_x = graph.get_tensor_by_name("Placeholder_1:0")
    input_y = graph.get_tensor_by_name("dense/BiasAdd:0")

    # 循环预测
    Pre = []
    while (PREDICT_UNIT != 0):
        predict_res = sess.run(input_y, feed_dict={input_x: test_x})  # 二维数组 [[0.5008618]]

        Pre.append(predict_res[-1])  # 一个预测数值

        test_x1 = test_x[1, :]
        test_x2 = test_x[1, 1:]
        test_x2 = np.append(test_x2, predict_res[-1, 0])
        test_x = np.vstack((test_x1, test_x2))

        PREDICT_UNIT = PREDICT_UNIT - 1

Pre = np.array(Pre).squeeze()  # 预测结果
# print Pre

# 画图
plt.plot(TEST_X)
plt.plot(np.append(TEST_X, Pre))
plt.savefig(mWDN_lstm.BASE_DIR + "/LOG_mWDN-LSTM_order_weight/res_predict.png")

# 输出数据返回前端
# print TEST_X
# print np.append(TEST_X, Pre)
